import request from '../service/api'
import Taro from "@tarojs/taro";

const delay = (time) => new Promise((resolve) => setTimeout(resolve, time || 0))
export default {
  namespace: 'cars',
  state: {
    myCar: {
     //  carNum: '豫A38C8T',
     //  brand: '一汽大众',
     //  detailInfo:{
     //    detail: '2020款 一汽大众 探岳GTE 1.4T 双离合变速器 豪华版'
     // },
    }
  },
  effects: {
    *init(){

    },
    *jumpCar(_, {call, put}){
      const {data, statusCode} = yield call(() => request.get('/mini/other/userCarVinList'));
      console.log('车辆', data);
      if (statusCode && statusCode === 200){
        yield put({
          type: 'setState',
          payload:{
            myCar: data?.data[0]
          }
        })
        // Taro.navigateTo({
        //   url: '/moduleB/pages/cars/index'
        // })
      } else {
        Taro.showToast({
          title: '车辆信息获取失败,请稍候重试',
          icon: 'none',
          duration: 1500
        })
      }
    },
    *addCar({payload}, {call, put}){
      console.log('payload', payload);
      const {data, statusCode} = yield call(() => request.post('/mini/other/bindUserCarVin', {...payload}));
      console.log('addCar', data);
      if (statusCode && statusCode === 200 && data.code === 200){
        Taro.showToast({
          title: '新增成功',
          icon: 'success',
          duration: 1500
        })
        yield call(() => delay(1000));
        Taro.navigateBack({
          delta: 1
        })
        yield put({
          type: 'jumpCar'
        })
      } else {
        Taro.showToast({
          title: data?.msg,
          icon: 'none',
          duration: 1500
        });
      }
    },
    *editCar({payload}, {call, put, select}){
      console.log('payload', payload);
      const {myCar = {}} = yield select(({cars}) => cars)
      const {data, statusCode} = yield call(() => request.post('/mini/other/update/vehicle', {...payload, id: myCar.id || ''}));
      console.log('editCar', data);
      if (statusCode && statusCode === 200 && data.code === 200){
        Taro.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 1500
        });
        yield call(() => delay(1000))
        Taro.navigateBack({
          delta: 1
        })
        yield put({
          type: 'jumpCar'
        })
      } else {
        Taro.showToast({
          title: data?.msg,
          icon: 'none',
          duration: 1500
        });
      }
    },
    *deleteCar(){

    }
  },
  reducers: {
    setState(state, {payload}){
        return {
          ...state,
          ...payload
        }
    }
  }
}
